//
//  ViewController.swift
//  rabbit
//
//  Created by yicheng on 16/11/18.
//  Copyright © 2016年 yicheng. All rights reserved.
//

import UIKit
import NetworkExtension


class HomeViewController: UIViewController {
    
    @IBOutlet var connectButton: UIButton!
    
    
    var status: VPNStatus {
        didSet(o) {
            updateConnectButton()
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        self.status = .off
        super.init(coder: aDecoder)
        NotificationCenter.default.addObserver(self, selector: #selector(onVPNStatusChanged), name: NSNotification.Name(rawValue: kProxyServiceVPNStatusNotification), object: nil)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.status = VpnManager.shared.vpnStatus
    }
    
    func onVPNStatusChanged(){
        self.status = VpnManager.shared.vpnStatus
    }
    
    func updateConnectButton(){
        switch status {
        case .connecting:
            connectButton.setTitle("连接中...", for: UIControlState())
            connectButton.backgroundColor = UIColor(rgb: 0x96CDCD)
        case .disconnecting:
            connectButton.setTitle("正在取消", for: UIControlState())
            connectButton.backgroundColor = UIColor(rgb: 0x96CDCD)
        case .on:
            connectButton.setTitle("取消连接", for: UIControlState())
            connectButton.backgroundColor = UIColor(rgb: 0x76d672)
            // 跳到VPN界面
            UIApplication.shared.openURL(URL(string: "App-prefs:root=General&path=VPN")!)
        case .off:
            connectButton.setTitle("连接", for: UIControlState())
            connectButton.backgroundColor = UIColor(rgb: 0x809df8)
        }
        connectButton.isEnabled = [VPNStatus.on,VPNStatus.off].contains(VpnManager.shared.vpnStatus)
        
    }
    
    @IBAction func connectTap(_ sender: AnyObject) {
        print("connect tap")
        if(VpnManager.shared.vpnStatus == .off){
            VpnManager.shared.connect()
        }else{
            VpnManager.shared.disconnect()
        }
    }
    
    
}

extension UIColor {
    convenience init(rgb: UInt) {
        self.init(
            red: CGFloat((rgb & 0xFF0000) >> 16) / 255.0,
            green: CGFloat((rgb & 0x00FF00) >> 8) / 255.0,
            blue: CGFloat(rgb & 0x0000FF) / 255.0,
            alpha: CGFloat(1.0)
        )
    }
}

